package org.spbsu.apco.server.monitoring.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spbsu.apco.common.monitoring.event.ServiceEvent;
import org.spbsu.apco.common.monitoring.event.TaskEvent;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Service to collect and manage events.
 *
 * User: mikpan
 * Date: 12/12/12
 * Time: 11:21 AM
 */
@Service(value = "MonitorService")
public class MonitorService implements EventManager {
    private static final Logger log = LoggerFactory.getLogger(MonitorService.class);

    private static final int MAX_BROKER_LOG_SIZE = 200; // 0 - unlimited
    private Queue<ServiceEvent> events = new LinkedList<ServiceEvent>();

    private static final int MAX_TASK_EVENT_LOG_SIZE = 150; // 0 -unlimited
    private Queue<TaskEvent> taskEvents = new LinkedList<TaskEvent>();
    //private Map<String, TaskEvent> taskId2event

    @Override
    public synchronized void addEvent(ServiceEvent e) {
        Assert.notNull(e.getMacAddress(), String.format("MAC address of the event originator is not defined. origId=%s", e.getOriginatorId()));
        e.generateNewId();
        events.add(e);
        log.info("Monitor added: {}", e);
        if (events.size() == MAX_BROKER_LOG_SIZE + 1) {
            events.remove();
        }
    }

    @Override
    public Queue<ServiceEvent> getEvents() {
        return new LinkedList<ServiceEvent>(events);
    }

    public synchronized void addTaskEvent(TaskEvent e) {
        e.generateNewId();
        taskEvents.add(e);
        if (taskEvents.size() == MAX_TASK_EVENT_LOG_SIZE + 1) {
            taskEvents.remove();
        }
    }

    public Queue<TaskEvent> getTaskEvents() {
        return new LinkedList<TaskEvent>(taskEvents);
    }

    public ServiceEvent getEventByTaskId(String taskId) {
        for (ServiceEvent event : events) {
            if (event.getTaskId().equals(taskId)) {
                return event;
            }
        }
        return null;
    }

}